import { BrowserWindow } from 'electron'

export interface WindowOptions {
  /**
   * 父窗口
   */
  parent?: BrowserWindow
  /**
   * 窗口标题
   */
  title?: string
  /**
   * 窗口唯一标识
   */
  flag: string
  /**
   * 窗口要加载的资源地址
   */
  url: string
  /**
   * 默认:800
   */
  width?: number
  /**
   * 默认:500
   */
  height?: number
  /**
   * 是否模态窗口. 默认:false
   */
  modal?: boolean
  /**
   * 点击关闭按钮，不关闭窗口，而是隐藏. 默认:true
   */
  closeIsHide?: boolean
}
class MutilWindow {
  private windowMap = new Map<string, BrowserWindow>()

  /**
   * 打开一个窗口加载本地资源
   * @param windowOptions
   */
  newWindowLoadFile(windowOptions: WindowOptions) {
    this.newWindow(windowOptions, true)
  }

  /**
   * 打开一个窗口加载网络资源
   * @param windowOptions
   */
  newWindowLoadURL(windowOptions: WindowOptions) {
    this.newWindow(windowOptions, false)
  }

  hide(flag: string) {
    const win = this.windowMap.get(flag)
    if (win) {
      win.hide()
    }
  }

  show(flag: string) {
    const win = this.windowMap.get(flag)
    if (win) {
      win.show()
    }
  }

  destroy(flag: string) {
    const win = this.windowMap.get(flag)
    if (win) {
      if (win.isDestroyed()) {
        win.destroy()
      }
      this.windowMap.delete(flag)
    }
  }

  destroyAll() {
    const winIter = this.windowMap.values()
    for (let win of winIter) {
      if (!win.isDestroyed()) {
        win.destroy()
      }
    }
    this.windowMap = new Map<string, BrowserWindow>()
  }

  private newWindow(windowOptions: WindowOptions, loadLocalFile: boolean) {
    const { width = 800, height = 500, url, flag, title, modal = false, closeIsHide = true } = windowOptions
    let win = this.windowMap.get(flag)
    if (win) {
      if (!win.isDestroyed()) {
        win.show()
        win.focus()
        return
      }
      this.windowMap.delete(flag)
    }
    win = new BrowserWindow({
      modal,
      title,
      width: width,
      height: height,
      show: false,
      autoHideMenuBar: true,
      webPreferences: {
        contextIsolation: true,
        nodeIntegration: true,
      },
    })
    win.once('ready-to-show', () => {
      win.show()
    })
    win.on('close', e => {
      if (closeIsHide) {
        win.hide()
        e.preventDefault()
        return false
      }
    })
    if (loadLocalFile) {
      win.loadFile(url)
    } else {
      win.loadURL(url)
    }
    win.setMenu(null)
    this.windowMap.set(flag, win)
    return win
  }
}

export const mutilWindowInstance = new MutilWindow()
